package com.uam.core.business;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.uam.core.config.ExecutorConfig;
import com.uam.core.config.UAMConfig;
import com.uam.core.dao.mysql.AircraftDao;
import com.uam.core.dao.mysql.PolygonV1Dao;
import com.uam.core.dao.mysql.TaskDao;
import com.uam.core.entity.constant.RedisConstants;
import com.uam.core.entity.constant.RedisLockKeyEnum;
import com.uam.core.entity.model.AircraftModel;
import com.uam.core.entity.model.PolygonV1;
import com.uam.core.entity.model.TaskModel;
import com.uam.core.service.RouteService;
import com.uam.core.tool.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.Polygon;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @author Administrator
 */
@Component
@Slf4j
public class RouteStatusInfo extends ParentBusiness {

    @Autowired
    private TaskDao taskDao = null;

    @Autowired
    private RouteService routeService;

    @Autowired
    private UAMConfig config;

    @Autowired
    private AircraftDao aircraftDao = null;

    @Autowired
    private PolygonV1Dao polygonV1Dao;

    @Autowired
    private OperationDbBusiness operationDbBusiness;

    @Autowired
    private SolveConflictBusiness conflictBusiness;

    @Autowired
    private RedissonClient redisson;

    @Autowired
    ExecutorConfig executorConfig;

    public List<TaskModel> taskRouteInfo() {
//        RLock lock = redisson.getLock(RedisConstants.ROUTE_KEY_LOCKE);

        //支持集群是部署
        List<TaskModel> taskResult = null;
        try {
//            boolean success = lock.tryLock();
//            if (!success) {
//                log.error("执行数据库错误：锁超时");
//                return taskResult;
//            }
            taskResult = this.taskDao.queryTaskModel();
        } catch (Exception e) {
            log.error("执行数据库错误：", e);
        } finally {
//            lock.unlock();
        }

        if (taskResult == null || taskResult.size() == 0) {
            return taskResult;
        }
        //航线规划和冲突解决
        trackPointInfo(taskResult);

        return  taskResult;
    }

    /**
     * 航线规划和冲突解决
     *
     * @param taskModelList
     * @return
     */
    public void trackPointInfo(List<TaskModel> taskModelList) {
        int row = taskModelList.size();
        try {
//            CountDownLatch countDownLatch = new CountDownLatch(row);
            for (int i = 0; i < row; i++) {
                TaskModel taskModel = taskModelList.get(i);
                try {
                    RouteStatusThread thread=  new RouteStatusThread(null, taskModel);
                    thread.run();
//                    executorConfig.getAsyncExecutor().execute(thread);
                } catch (Exception e) {
                    log.error("数据解析错误：{}", JSONObject.toJSONString(taskModel), e);
                }
            }
//            countDownLatch.await();
        } catch (Exception e) {
            log.error("执行数据错误：", e);
        }
    }


    /**
     * 获取路径
     *
     * @param aircraft
     * @param task
     * @return
     */
    public JSONObject getPath(AircraftModel aircraft, TaskModel task) {
        RouteService.RouteResultWithAircraftPositions positions = SmartRouteUtils.smartRoute(config, aircraft, task, routeService);
        if(positions == null){
            return null;
        }
        JSONObject route = positions.getRouteResult();
        return route;
    }


    /**
     * 线程启用接口
     *
     * @author uam
     * @date 2023/12/31
     */
    public class RouteStatusThread implements Runnable {

        private CountDownLatch countDownLatch;

        private TaskModel taskModel;

        public RouteStatusThread(CountDownLatch countDownLatch, TaskModel taskModel) {
            this.countDownLatch = countDownLatch;
            this.taskModel = taskModel;
        }

        @Override
        public void run() {
            try {
                AircraftModel aircraftModel = aircraftDao.detailAircraft(taskModel.getAircraftId()).getData().get(0);
                JSONObject path = getPath(aircraftModel, taskModel);
                if(path == null){
                    log.warn("获取航线信息为空，任务航线规划失败");
//                    countDownLatch.countDown();
                    return;
                }


                //点对应时间戳
                JSONArray points = pointsTime(aircraftModel, path.getJSONObject("points"), taskModel);
                System.out.println("规划航线-->"+JSONArray.toJSONString(points));

                //判断是满足续航
                JSONArray sTime=points.getJSONArray(0);
                JSONArray eTime=points.getJSONArray(points.size()-1);
                double maxDuration = aircraftModel.getMaxDuration();
                long time=  (eTime.getDate(4).getTime()-sTime.getDate(4).getTime())/1000;
                long maxTime=time/60;
                if (maxTime > maxDuration) {
                    taskDao.rejectTask(taskModel.getId(),"任务所选模型续航不足！");
                }else {
                    operationDbBusiness.dbInfo(points, aircraftModel, taskModel, path);
                }
            } catch (Exception e) {
                log.error("数据解析错误 ", e);
                taskDao.rejectTask(taskModel.getId(),"航线路线规划错误，"+e.getMessage());
            }
//            countDownLatch.countDown();
        }
    }
}
